package com.nali.dal.statement;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.nali.dal.expression.ExpressionValue;
import com.nali.dal.expression.query.Criteria;

public class SelectBuilder {
	private DalTemplate template;
	private String statement;
	private List<ExpressionValue<Criteria>> conds = new LinkedList<ExpressionValue<Criteria>>();

	public SelectBuilder(DalTemplate template, String statement) {
		super();
		this.template = template;
		this.statement = statement;
	}
	
	public SelectBuilder cond(String property, Criteria criteria, Object value) {
		conds.add(new ExpressionValue<Criteria>(property, criteria, (Serializable)value));
		return this;
	}
	
	public SelectBuilder regexMatch(String property, String regex) {
		conds.add(new ExpressionValue<Criteria>(property, Criteria.like, regex));
		return this;
	}
	
	public long count() {
		return template.count(statement, getConditions());
	}
	
	@SuppressWarnings("unchecked")
	private ExpressionValue<Criteria>[] getConditions() {
		ExpressionValue<Criteria>[] condArr = new ExpressionValue[conds.size()];
		return conds.toArray(condArr);
	}

	public List<Map<String, Object>> select() {
		return template.select(statement, getConditions());
	}

	public List<Map<String, Object>> select(int offset, int limit) {
		return template.select(statement, getConditions(), offset, limit);
	}

	public int selectUpsert() {
		return template.selectUpsert(statement, getConditions());
	}

}
